package com.mck.service.impl;

import com.mck.anno.OperationLog;
import com.mck.entity.Classname;
import com.mck.mapper.ClassnameMapper;
import com.mck.service.ClassnameService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.List;

/**
 * @version 1.0.0
 * @Author mck
 * @Date 2025/1/27 下午5:53
 * @注释
 */

@Service
public class ClassnameServiceImpl implements ClassnameService {

    @Autowired
    private ClassnameMapper classnameMapper;

    // 获取班级列表
    @Override
    @Cacheable(value = "classnames", key = "'all'", unless = "#result.isEmpty()")
    public List<Classname> getClassnameList() {
        return classnameMapper.getClassnameList();
    }

    // 根据id获取班级信息
    @Override
    @Cacheable(value = "classname", key = "#classnameId", unless = "#result == null")
    public Classname getClassnameById(Integer classnameId) {
        return classnameMapper.getClassnameById(classnameId);
    }

    // 添加班级
    @OperationLog
    @Override
    @CacheEvict(value = "classnames", key = "'all'")
    public void addClassname(Classname classname) {
        // 补全属性
        classname.setCreateTime(LocalDate.now());

        classnameMapper.addClassname(classname);
    }

    // 添加班级列表
    @OperationLog
    @Override
    @CacheEvict(value = "classnames", key = "'all'")
    public void addClassnameList(List<Classname> classnameList) {
        // 批量导入班级
        for (Classname classname : classnameList) {
            // 补全属性
            classname.setCreateTime(LocalDate.now());

            classnameMapper.addClassname(classname);
        }
    }

    // 更新班级信息
    @OperationLog
    @Override
    @Caching(
            evict = {
                    @CacheEvict(value = "classnames", key = "'all'"),
                    @CacheEvict(value = "classname", key = "#classname.classId")
            }
    )  // @Caching同时执行多个缓存操作, evict删除缓存
    public void updateClassname(Classname classname) {
        classname.setUpdateTime(LocalDate.now());

        classnameMapper.updateClassname(classname);
    }

    // 删除班级
    @OperationLog
    @Override
    @Caching(evict = {
            @CacheEvict(value = "classnames", key = "'all'"),
            @CacheEvict(value = "classname", key = "#classId")
    })
    public void deleteClassname(Integer classId) {
        classnameMapper.deleteClassname(classId);
    }
}
